const app = getApp();
import {
    getStorage,
    setStorage
} from "../../utils/localStorage.js";
import {
    baseUrl
} from "../../api/request";
import {
    getMapDistance
} from "../../utils/address"
import {
    routeRecomtion_List,
    intelPlaning_List,
    intelPlaning_Record,
    znRoute_Delete,
    obtainMy_List,
    recommendMy_List,
    routeLikes,
    getRuralRoutes_List,
    specialSubject_List
} from "../../api/luxian.js";

const scroll = {
    page: 1,
    pagesize: 20,
    canLoad: true,
    listEnd: false,
    triggered: false,
}

Component({
    properties: {},
    data: {
        //图片地址
        baseUrl: baseUrl,
        //自定义导航栏组件参数
        navData: {
            title: '',
            level: 5
        },
        pageIndex: 0,
        recommendIndex: 0,
        routeIndex: 0,
        historyIndex: 0,
        triggered: false,
        classification: [],
        recommend: [{
            name: '山水相依，古韵武义',
            img: '../../image/img/组 806.png',
            type: '自驾玩法',
            way: '溪北村 — 新宅村',
            collect: 32,
            isCollect: true
        }],
        hot: [],
        // 乡村标签
        ruralLabel: [],
        // 标签下所属路线
        routeList: [],
        history: [{
            ...JSON.parse(JSON.stringify(scroll)),
            name: '旅行开始',
            url: '',
            list: [],
        }, {
            ...JSON.parse(JSON.stringify(scroll)),
            name: '点赞路线',
            url: '',
            list: [],
        }, {
            ...JSON.parse(JSON.stringify(scroll)),
            name: '路线暂存',
            url: '',
            list: [],
        }],
        pageTop: app.globalData.navHeight + app.globalData.navTop,
        pageBottom: app.globalData.bottomLift - 12,
    },
    properties: {
        luxianNavIndex: {
            type: Number,
            value: 0,
            observer: function (val) {
                console.log(val)
                this.setData({
                    pageIndex: val
                });
            }
        },
    },
    lifetimes: {
        attached() {
            if (app.loginState()) return;
            // this.getArea()
            this.allTopics()
            // this.allMyTopics()
            this.recommenMyTopics()
            this.getRuralTags()
            this.getRuralRoutes()
        },
        detached() {},
    },
    pageLifetimes: {
        show() {

        },
    },
    methods: {
        // 获取乡村标签下的路线
        async getRuralRoutes(dictValue = -1){
            console.log('发起请求了');
            if(dictValue < 0){
                let result = await getRuralRoutes_List()
                this.setData({routeList:result.data.rows})
                console.log('获取乡村标签下的路线',this.data.routeList);
            }else{
                let result = await getRuralRoutes_List({dictValue})
                this.setData({routeList:result.data.rows})
                console.log('获取乡村标签下的路线',this.data.routeList);
            }
        },
        //获取乡村标签
        async getRuralTags() {
            let result = await app.getDict("village_label")
            this.setData({
                ruralLabel: [{ dictLabel: '推荐'} , ...result.data]
            });
            console.log('获取乡村标签',this.data.ruralLabel);
        },
        // 点赞/取消
        isLike(e) {
            let {
                index,
                islikestate
            } = e.currentTarget.dataset
            this.setData({
                [`recommend[${index}].likeState`]: !islikestate
            })
            console.log(!islikestate);
        },
        // 获取推荐和热门路线数据
        async recommenMyTopics(type = 1) {
            let result = await recommendMy_List({
                type
            })
            // console.log('路线数据', result.data.rows);
            // console.log('type', type);
            this.setData({
                recommend: result.data.rows
            })
            // console.log('修改后', this.data.recommend);
            this.data.recommend.forEach((item, index) => {
                let villageNameArray = item.villageName.split(',')
                let wayArray = []
                wayArray.push(villageNameArray[0])
                wayArray.push(villageNameArray[villageNameArray.length - 1])
                let way = wayArray.join(' ~ ')
                // console.log(way);
                this.setData({
                    [`recommend[${index}].way`]: way
                })
            })
        },
        // 小程序获取我的路线信息
        async allMyTopics(type = 0) {
            let result = await obtainMy_List({
                type
            })
            // console.log('历史规划', result.data.rows);
            // console.log('type', type);
            this.setData({
                [`history[${type}].list`]: result.data.rows
            })
            console.log('修改后', this.data.history[type].name, this.data.history[type].list);
        },
        // 获取所有专题信息
        async allTopics() {
            let result = await specialSubject_List()
            this.setData({
                classification: result.data.data
            })
        },
        // 点击跳转详情页面
        handleTapTo() {
            wx.navigateTo({
                url: '/pages/luxianXQ/luxianXQ',
                events: {
                    // 这里用ES6的语法糖省略了  :function   
                    // 原式子 acceptDataFromOpenedPage: function(data) {}
                    //data就是B页面回传的数据
                    tDataFromOpenedPage(data) {
                        // 一旦B页面通过事件通道将数据回传给了A，就会执行设置代码
                        console.log('接收到B页面反向传参的数据：', data)
                    }
                },
            })
        },
        //自定义导航栏切换点击事件
        lxNavEvent(e) {
            this.setData({historyIndex:0})
            this.allMyTopics()
            this.setData({
                pageIndex: e.detail
            })
        },
        getArea() {
            let list = [];
            for (let i = 0; i < 5; i++) {
                let one = JSON.parse(JSON.stringify(scroll));
                one.name = '金华' + i;
                one.list = [{
                    title: '山水相依，古韵武义',
                    image: '../../image/img/image3.png',
                    day: 7,
                    scenic: 7,
                    collect: 7,
                    isCollect: true,
                    distance: '132.56km',
                    village: [{
                            name: '范西村',
                            image: '../../image/img/蒙版组 3.png'
                        },
                        {
                            name: '范西村',
                            image: '../../image/img/蒙版组 3.png'
                        },
                        {
                            name: '范西村',
                            image: '../../image/img/蒙版组 3.png'
                        },
                        {
                            name: '范西村',
                            image: '../../image/img/蒙版组 3.png'
                        },
                        {
                            name: '范西村',
                            image: '../../image/img/蒙版组 3.png'
                        },
                        {
                            name: '范西村',
                            image: '../../image/img/蒙版组 3.png'
                        }
                    ]
                }];
                list.push(one)
            }
            this.setData({
                route: list
            })
        },
        swiperChg(e) {
            this.setData({
                historyIndex: e.detail.current
            })
        },
        // 历史规划切换
        indexChgHistory(e) {
            let {
                key,
                index
            } = e.currentTarget.dataset;
            this.setData({
                [key + 'Index']: index
            })
            console.log('历史规划切换',key, index);
            this.allMyTopics(index)
        },

        // 热门推荐切换
        indexChgHot(e) {
            let {
                key,
                index
            } = e.currentTarget.dataset;
            this.setData({
                [key + 'Index']: index
            })
            this.recommenMyTopics(index + 1)
        },

        // 乡村标签推荐切换
        indexruRalTags(e) {
            let {
                key,
                index
            } = e.currentTarget.dataset;
            console.log('乡村标签推荐切换',key, index);
            this.setData({
                [key + 'Index']: index
            })
            this.getRuralRoutes(index - 1)
        },
        refresh() {

            // this.getlist()
        },
        getMore() {},
        getHistory(i) {
            return false;
            if (!this.data.history[i].canLoad) {
                return false;
            }
            let list = this.data.history;
            list[i].canLoad = false;
            ajax.request("get", "/app/invoice/list", {
                invoiceStatus: list[i].invoiceStatus,
                pageNum: list[i].page,
                pageSize: list[i].pagesize
            }).then(res => {
                list[i].triggered = false;
                let newlist = res.rows;
                list[i].canLoad = true;
                // console.log(res)
                list[i].list = [
                    ...list[i].list,
                    ...newlist
                ]
                if (newlist.length < list[i].pagesize) {
                    this.setData({
                        ['history.' + i + '.listEnd']: true
                    })
                } else {
                    list[i].page++
                }
                this.setData({
                    history: list
                })
            }).catch(err => {
                list[i].triggered = false;
                list[i].canLoad = true;
                this.setData({
                    history: list
                })
            })
        },
        historyRefresh(e) {
            // console.log(e)
            let index = e.currentTarget ? e.currentTarget.dataset.index : e;
            let list = this.data.history;
            list[index] = {
                ...list[index],
                ...scroll
            };
            this.setData({
                history: list
            })
            this.getHistory(index)
        },
        getHistoryMore(e) {
            // console.log(e)
            let index = e.currentTarget.dataset.index;
            if (this.data.history[index].canLoad && !this.data.history[index].listEnd) {
                this.getHistory(index)
            }
        },
        openClass(e) {
            let {
                index,
                topicid
            } = e.currentTarget.dataset;
            let data = this.data.classification[index];
            // console.log('topicId',e.currentTarget.dataset);
            // console.log('topicId',topicid);

            wx.navigateTo({
                url: '/pagesLuxian/pages/classification/index?name=' + data.topicName + '&topicId=' + topicid,
            })
        }
    }
})